package com.mxsoft.web;

import com.mxsoft.util.ThreadPoolExecutorUtils;
import com.mxsoft.util.UserThreadState;
import com.mxsoft.util.UserUtils;
import com.mxsoft.web.bean.UserObj;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HellowordServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserObj currentUser = UserUtils.getCurrentUser();
        System.out.println(currentUser.getName() + "->" + currentUser.hashCode());

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                UserObj user = UserUtils.getCurrentUser();
//                System.out.println("自线程： " + (user == null ? "user为null" : user.getName() + "->" + user.hashCode()));
//            }
//        }).start();


        ThreadPoolExecutorUtils.execute(new UserRunnable(new UserThreadState(currentUser)));

//        super.doGet(req, resp);

        resp.getWriter().write("success");
        resp.getWriter().flush();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

class UserRunnable implements Runnable {

    UserThreadState userThreadState;

    public UserRunnable( UserThreadState userThreadState) {
        this.userThreadState = userThreadState;
    }

    @Override
    public void run() {
        userThreadState.bind();
        UserObj user = UserUtils.getCurrentUser();

        //输出子线程的user信息
        System.out.println("自线程： " + (user == null ? "user为null" : user.getName() + "->" + user.hashCode()));
        userThreadState.restore();

        //输出富显成的user信息
        UserObj currentUser = UserUtils.getCurrentUser();
        System.out.println("original: " + currentUser.getName()+"->" + currentUser.hashCode());
    }
}

